package com.rongchuang.service;

import com.rongchuang.dto.LoginDTO;
import com.rongchuang.entity.User;
import com.rongchuang.exception.CustomException;
import com.rongchuang.repository.UserRepository;
import com.rongchuang.util.PasswordEncryptor;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.Objects;
import java.util.UUID;

@CrossOrigin
@Service
public class LoginService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private TokenService tokenService;

    /**
     * 登录
     * @param mobile 账号
     * @param password 用户密码
     * @return 登录信息
     */
    public LoginDTO login(String mobile, String password) {
        if (StringUtils.isBlank(mobile)) {
            throw new CustomException(-1, "请输入账号");
        }
        if (StringUtils.isBlank(password)) {
            throw new CustomException(-1, "请输入密码");
        }
        User user = userRepository.getUserByMobile(mobile);
        if (Objects.isNull(user)) {
            throw new CustomException(-1, "账号不存在");
        }
        String mdPassword = PasswordEncryptor.encryptPassword(password);
        if (!mdPassword.equals(user.getPassword())) {
            throw new CustomException(-1, "密码错误");
        }

        // token 保存
        String token = UUID.randomUUID().toString();
        tokenService.saveToken(user.getId(), token);
        return new LoginDTO(user.getUsername(), token);
    }

    /**
     * 退出登录
     * @param token token
     */
    public void logout(String token) {
        tokenService.deleteToken(token);
    }

    /**
     * 修改密码
     * @param id 用户id
     * @param oldPassword 老密码
     * @param newPassword 新密码
     */
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        User user = userRepository.getById(id);
        String oldMdPassword = PasswordEncryptor.encryptPassword(oldPassword);
        if (!oldMdPassword.equals(user.getPassword())) {
            throw new CustomException(-1, "密码错误");
        }
        String newMdPassword = PasswordEncryptor.encryptPassword(newPassword);
        user.setPassword(newMdPassword);
        userRepository.save(user);
    }
}
